package com.chain.qs.modules.biz.web;


import com.chain.qs.common.config.Global;
import com.chain.qs.common.utils.Collections3;
import com.chain.qs.common.web.BaseController;
import com.chain.qs.modules.biz.entity.DeviceItem;
import com.chain.qs.modules.biz.entity.Station;
import com.chain.qs.modules.biz.entity.StationGroupCfgExtend;
import com.chain.qs.modules.biz.service.StationGroupCfgExtendService;
import com.chain.qs.modules.biz.service.StationGroupService;
import com.chain.qs.modules.biz.service.StationService;
import com.chain.qs.modules.sys.entity.Office;
import com.chain.qs.modules.sys.utils.UserUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 设备类型Controller
 *
 * @author Wang zhiping
 */
@Controller
@RequestMapping(value = "${adminPath}/biz/sgcfg")
public class StationGroupCfgController extends BaseController {
    @Resource
    private StationGroupCfgExtendService sgcfgService;
    @Resource
    private StationService stationService;
    @Resource
    private StationGroupService sgroupService;

    @ModelAttribute
    public Station get(@RequestParam(required = false) String stationId) {
        Station station = null;
        if (stationId != null) {
            station = stationService.get(stationId);
        }
        return station;
    }

    @RequestMapping(value = {"list", ""})
    public String list(String sgroupId, Model model) {
        List<StationGroupCfgExtend> list = sgcfgService.equlistByGroup(sgroupId);
        model.addAttribute("list", list);
        model.addAttribute("sgroupId", sgroupId);
        return "modules/biz/stationGroupCfgList";
    }

    //    id=${cfg.sgcfg.id}&sgroup.id=${cfg.sgcfg.sgroup.id}&gitem.id=${cfg.gitem.id}
    @RequestMapping(value = "form")
    public String form(@RequestParam(required = false, value = "sgroupId") String sgroupId, @RequestParam(required = false, value = "groupId") String groupId, @RequestParam(required = false, value = "gitemId") String gitemId, Model model) {

        StationGroupCfgExtend cfg2 = sgcfgService.getOne(sgroupId, groupId, gitemId);
        model.addAttribute("cfg2", cfg2);
        model.addAttribute("sgroupId", sgroupId);
        return "modules/biz/stationGroupCfgForm";
    }

    @ResponseBody
    @RequestMapping(value = "save")//@Valid
    public String save(StationGroupCfgExtend cfg2) {
//        String ss=temp.getSgcfg().getId();
        if (cfg2.getSgcfg().getId() == null || cfg2.getSgcfg().getId().equals("")) {
            sgcfgService.save(cfg2);
        } else {
            sgcfgService.modify(cfg2);
        }
//        更改站组完整性
        String sgroupId = cfg2.getSgroup().getId();
        int integrityValue = sgcfgService.countIpModelNull(sgroupId);
        if(integrityValue==0){
            sgroupService.updateIntegrityYes(sgroupId);
        }else {
            sgroupService.updateIntegrityNo(sgroupId);
        }
        return "success";
    }


    @RequestMapping(value = "delete")
    public String delete(StationGroupCfgExtend sgcfg, RedirectAttributes redirectAttributes) {
        if (Global.isDemoMode()) {
            addMessage(redirectAttributes, "演示模式，不允许操作！");
            return "redirect:" + adminPath + "/biz/sgcfg/";
        }
        sgcfgService.delete(sgcfg);
        addMessage(redirectAttributes, "删除设备成功");
        return "redirect:" + adminPath + "/biz/sgcfg/";
    }

    @ResponseBody
    @RequestMapping(value = "getlistbyoffid")
    public Map<String, List<DeviceItem>> getListByOfficeId(String id) {
        List<StationGroupCfgExtend> list = sgcfgService.getListByOfficeId(id);
        List<DeviceItem> deviceItems = new ArrayList<>(list.size());
        DeviceItem item;
        String url;
        for (StationGroupCfgExtend sg : list) {
            item = new DeviceItem();
            item.setStationId(sg.getStation().getId());
            item.setGroupId(sg.getGroup().getId());
            item.setType(sg.getModelName());
            item.setDeviceClass(sg.getModelName());
            if (sg.getSgcfg() != null) {
                url = sg.getSgcfg().getIpPort();
                if (StringUtils.isNotBlank(sg.getSgcfg().getOther1()))
                    url = url + ":" + sg.getSgcfg().getOther1();

                if (StringUtils.isNotBlank(sg.getSgcfg().getOther2()))
                    url = url + ":" + sg.getSgcfg().getOther2();

            }
            item.setConUrl(sg.getSgcfg().getIpPort());
            deviceItems.add(item);
        }

        Map<String, List<DeviceItem>> map = new HashMap<>();
        map.put("items", deviceItems);
        return map;
    }


    @RequestMapping(value = "itemlist")
    public String itemlist(HttpServletResponse response,  String sgroupId) {
        List<StationGroupCfgExtend> list = sgcfgService.equlistByGroup(sgroupId);
        return renderString(response,list);
    }
    @RequestMapping(value = "itemlistForTrans")
    public String itemlistForTrans(HttpServletResponse response,  String sgroupId) {
        List<StationGroupCfgExtend> list = sgcfgService.equlistForTransByGroup(sgroupId);
        return renderString(response,list);
    }
    @RequestMapping(value = "itemlistById")
    public String itemlistById(HttpServletResponse response,  String sgroupId) {
        List<StationGroupCfgExtend> list = sgcfgService.itemlistById(sgroupId);
        return renderString(response,list);
    }
    @RequestMapping(value = "graphItemlist")
    public String graphItemlist(HttpServletResponse response,  String sgroupId) {
        List<StationGroupCfgExtend> list = sgcfgService.graphItemlist(sgroupId);
        return renderString(response,list);
    }

    /**
     * 获取指定站点的系统-组-设备 三级配置信息
     */
    @RequestMapping(value = "getStationConf")
    public Object getStationConf(HttpServletResponse response,String stationCode){
        Map map = Maps.newHashMap();
        List<HashMap<String,String>> lists;
        boolean isExist = false;
        if(StringUtils.isNotEmpty(stationCode)){
            List<Office> officeList = UserUtils.getStationList();
            for(Office office:officeList){
                if(office.getCode().equals(stationCode)){
                    isExist = true;
                    break;
                }
            }
            if(isExist){
                lists =  sgcfgService.getCfgByStationCode(stationCode);
                if(!Collections3.isEmpty(lists)){
                    map = toTransformMap(lists);
                }
            }
        }
        return renderString(response,map);
    }

    private Map toTransformMap( List<HashMap<String,String>> lists){
        Map map = Maps.newHashMap();
        Map<String,Object> tempWholeSys = Maps.newHashMap();
        Map<String,Object> tempWholeBasic = Maps.newHashMap();
        Map<String,String> sysFlagMap = Maps.newHashMap();

        Map<String,String> basicFlagMap = Maps.newHashMap();

        for(HashMap<String,String> item:lists){
            if("1".equals(String.valueOf(item.get("grpType"))) && !basicFlagMap.containsKey(item.get("sGrpId"))){
                Map tempBasicMap = Maps.newHashMap();

                tempBasicMap.put("sGrpName",item.get("sGrpName"));
                tempBasicMap.put("sGrpId",item.get("sGrpId"));
                tempBasicMap.put("grpId",item.get("grpId"));
                tempBasicMap.put("equips",getEquips(String.valueOf(item.get("sGrpId")),lists));
                basicFlagMap.put(item.get("sGrpId"),"");
                tempWholeBasic.put(item.get("sGrpId"),tempBasicMap);
            }
            if("2".equals(String.valueOf(item.get("grpType"))) && !sysFlagMap.containsKey(item.get("sGrpId"))){
                Map tempSysMap = Maps.newHashMap();

                tempSysMap.put("sGrpName",item.get("sGrpName"));
                tempSysMap.put("sGrpId",item.get("sGrpId"));
                tempSysMap.put("grpId",item.get("grpId"));
                tempSysMap.put("equips",getEquips(String.valueOf(item.get("sGrpId")),lists));
                sysFlagMap.put(item.get("sGrpId"),"");
                tempWholeSys.put(item.get("sGrpId"),tempSysMap);
            }
        }
        map.put("basic",tempWholeBasic);
        map.put("sys",tempWholeSys);
        return map;
    }

    private Map<String ,Map<String,String>> getEquips(String grpId,List<HashMap<String,String>> lists){
        Map<String,Map<String,String>> wholeMap = Maps.newHashMap();
        Map<String,String> map;
        for(HashMap<String,String> item:lists){
            map = Maps.newHashMap();
            if(grpId.equals(String.valueOf(item.get("sGrpId")))){
                map.put("id",String.valueOf(item.get("id")));
                map.put("equipName",item.get("equipName"));
                map.put("equipType",item.get("equipType"));
                wholeMap.put(item.get("id"),map);
            }
        }
        return wholeMap;
    }
}
